package com.yycx.module.bus.provider.handler.haiying.tasktodo.backorder;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.yycx.bpm.provider.common.handler.ProcInstDeleteHandler;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.utils.ApiAssert;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.provider.service.hy.BusPaymentOrderService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import com.yycx.module.bus.provider.service.hy.HyRemoteOrderService;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.provider.service.SysCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 退货订单流程实例删除回调
 *
 * @author zyf
 */
@Component
@DSTransactional
@Slf4j
public class HyBackOrderProcDeleteHandler implements ProcInstDeleteHandler {

    @Resource
    private HyOrderService orderService;
    @Resource
    private SysCompanyService companyService;

    @Resource
    private BusPaymentOrderService paymentOrderService;

    @Resource
    private HyRemoteOrderService hyRemoteOrderService;

    @Override
    public boolean support(String processDefinitionKey) {
        return false;
    }

    @Override
    @DSTransactional
    public ResultBody success(String businessKey, String processInstanceId) {
        HyOrder order = orderService.getById(businessKey);
        Long companyId = order.getCompanyId();
        SysCompany company = companyService.getById(companyId);
        String dbName = company.getBusinessScope();
        ApiAssert.isNotEmpty("账套实例未配置", dbName);
        Integer sourceType = order.getSourceType();
        //发货状态
        Integer sendState = FlymeUtils.getInteger(order.getSendState(), 0);
        //删除海鹰订单
        if (FlymeUtils.isNotEmpty(dbName)) {
            if (sendState.equals(1)) {
                orderService.updateOrderState(businessKey, null, CommonConstants.INT_0, CommonConstants.INT_0, 1);
                return ResultBody.ok();
            }
            //未收货
            if (sendState.equals(0)) {
                //是否生成收货单
                Integer count = hyRemoteOrderService.countByOrderId(dbName, businessKey);
                //必须是结算系统录入的才能删除海鹰定单信息
                if (count.equals(0) && sourceType.equals(2)) {
                    orderService.updateOrderState(businessKey, null, CommonConstants.INT_0, CommonConstants.INT_0, 0);
                    return ResultBody.ok();
                } else {
                    return ResultBody.failed("订单已提单禁止撤销");
                }
            }

        }
        return ResultBody.ok();
    }
}
